/**
 * @copyright (C) COPYRIGHT 2022 Fortiortech Shenzhen
 * @file      MotorControlFunction.c
 * @author    Fortiortech  Appliction Team
 * @since     Create:2022-08-05
 * @date      Last modify:2022-08-05
 * @note      Last modify author is Leo.li
 * @brief
 */
#include <MyProject.h>

/**
 * @brief        RSD 外部中断睡眠引脚设置
 * @date         2022-09-13
 */
void SleepMode_Init(void)
{
    ClrBit(P1_OE, P11); // config P11 as input
    ClrBit(P1_PU, P11); // diasable P11 Pull Up
    ClrBit(P1_IF, P11); // clear P11 interrupt flag
    ClrBit(P1_IE, P11); // config P11 as the source of EXTI1
    IT11 = 1;
    IT10 = 0; // 00: posedge mode interrupt，01: negedge mode interrupt，1x: edge-change mode interrupt
    SetBit(IP0, PX11);
    SetBit(IP0, PX10); // 中断优先级别0，中断优先级最高
    EX1 = 1;           // 使能外部中断1, P11位外部中断输入硬件
    EA = 1;            // 使能全局中断
}

/**
 * @brief        进入睡眠模式
 * @date         2022-09-13
 */
void SleepMode(void)
{
    static uint16 SleepDelayCout = 0;

    SleepDelayCout++;

    if ((SleepDelayCout >= 6000) && (foc_control.sleep_flag == 0)) // 最大65530，若要再大，需改数据类型
    {
        MOE = 0;

        /******睡眠模式初始化**********/
        SleepMode_Init();

        ClrBit(DRV_CR, FOCEN); // 关闭FOC
        ClrBit(ADC_CR, ADCEN);
        ClrBit(CCFG1, WDT_EN); // 关闭WDT
        // 关闭运放
        ClrBit(AMP_CR0, AMP0EN); // AMP0 Enable
        ClrBit(AMP_CR0, AMP1EN); // AMP1 Enable
        ClrBit(AMP_CR0, AMP2EN); // AMP2 Enable
        // 关闭比较器
        ClrBit(CMP_CR1, CMP3EN); // CMP3 Enable
        // 关闭VREF
        SetBit(VREF_VHALF_CR, 0x00);

        /*- 没有引出的IO配置上拉，引出IO每个都需要有固定状态—-*/
        P2_OE = P21 | P22 | P23 | P24 | P25 | P26 | P27;
        P2_PU = P25;
        GP21 = 0;
        GP22 = 0;
        GP23 = 0;
        GP24 = 0;
        GP25 = 1;
        GP26 = 0;
        GP27 = 0;

        P3_OE = P30 | P31 | P34 | P36 | P37;
        P3_PU = P32 | P35; // 需确认这些端口能接受上拉
        GP30 = 0;
        GP31 = 0;
        GP34 = 0;
        GP36 = 0;
        GP37 = 0;

        P4_OE = P43 | P44 | P46;
        P4_PU = P41 | P42 | P45;
        GP43 = 0;
        GP44 = 0;
        GP46 = 0;

        P0_OE = P00 | P01 | P02 | P03 | P04 | P05 | P06 | P07;
        P0_PU = P01 | P02 | P03 | P04 | P05 | P06; // 需确认这些端口能接受上拉
        GP00 = 0;
        GP01 = 0;
        GP02 = 1;
        GP03 = 1;
        GP04 = 1;
        GP06 = 1;
        GP07 = 0;

        /*-  P10和P11为开漏硬件上需要根据实际加上拉 睡眠模式下，这两个引脚不要配置，否则会出现灌电流-*/
        P1_OE = P12 | P13 | P14 | P15 | P16 | P17;
        P1_PU = 0; // 需确认这些端口能接受上拉
        GP12 = 0;
        GP13 = 0;
        GP14 = 0;
        GP15 = 0;
        GP16 = 0;
        GP17 = 0;

        P4_OE = P43 | P44;
        P4_PU = P41 | P42 | P45 | P46;
        GP43 = 0;
        GP44 = 0;

        SleepDelayCout = 0;
        foc_control.sleep_flag = 1;

        SetBit(CCFG1, VBB_DIS); // 关闭HVIC供电     ClrBit(CCFG1, VBB_DIS);  //使能输出后需要延时等待1ms以上
        SetBit(P1_IE, P11);     // config P11 as the source of EXTI1
        SetBit(PCON, STOP);
    }
}
